package chatuidemo.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.ysm.smfu.R;
import com.ysm.smfu.activity.BaseActivity;
import com.ysm.smfu.bean.Friend;
import com.ysm.smfu.contans.SpKey;
import com.ysm.smfu.manager.GlideCircleTransform;
import com.ysm.smfu.utils.JsonUtil;
import com.ysm.smfu.utils.SignUtil;
import com.ysm.smfu.utils.PrintUtil;
import com.ysm.smfu.utils.ToastUtils;
import com.ysm.smfu.utils.UIUtils;
import com.ysm.smfu.welcome.SharedConfig;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Collection;
import java.util.Map;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import chatuidemo.db.DBManager;
import okhttp3.Call;

/**
 * Created by Administrator on 2016/10/20.
 */
public class AddFriendsActivity extends BaseActivity {

    @BindView(R.id.search_img)
    ImageView searchImg;
    @BindView(R.id.search_nc)
    TextView searchNc;
    @BindView(R.id.sex)
    TextView sex;
    @BindView(R.id.search_sr)
    TextView searchSr;
    @BindView(R.id.search_dq)
    TextView searchDq;
    @BindView(R.id.title_body)
    TextView titleBody;
    @BindView(R.id.mainActivity_topbar_img)
    ImageView mainActivityTopbarImg;
    private String userId;
    private ProgressDialog progressDialog;
    private Intent intent;
    private String name;
    private String myID;
    private String loginId;
    private String pwd;
    private Friend friend;


    @Override
    protected void initViews() {
        super.initViews();
        setContentView(R.layout.addfriends);
        ButterKnife.bind(this);
        getconfig();
        getUserInfo(userId);
    }

    private void getconfig() {
        titleBody.setText("添加好友");
        mainActivityTopbarImg.setVisibility(View.GONE);
        userId = getIntent().getStringExtra(SpKey.USERID);
        name = new SharedConfig(UIUtils.getContext()).getCommoneSp().getString(SpKey.NAME, "");
        SharedPreferences currShared = new SharedConfig(UIUtils.getContext(), name).getPrivateSp();
        myID = currShared.getString(SpKey.USERID, "");
        pwd = currShared.getString(SpKey.PWD, "");
        loginId = currShared.getString(SpKey.LOGINID, "");
    }

    /**
     * 根据用户id获取用户信息
     *
     * @param id /user/userCenter
     */
    private void getUserInfo(String id) {
        String nonce = String.valueOf(new Random().nextInt());
        String timestamp = SignUtil.getTimeStamp(System.currentTimeMillis());
        String signLogin = SignUtil.signLogin(name, pwd, timestamp, nonce);
        OkHttpUtils.post().url(SpKey.BASEURL + "/user/userCenter")
                .addParams("id", id)
                .addParams("nonce", nonce)
                .addParams("timestamp", timestamp)
                .addParams("signLogin", signLogin)
                .addParams("loginId", loginId)
                .addParams("sign", SignUtil.signForGetUserInfo(id, nonce, timestamp, signLogin, loginId))
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                PrintUtil.printRespones("添加联系人" , response);
                String state = JsonUtil.getState(response);
                if (TextUtils.equals(state, "1")) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String user = jsonObject.optString("user");
                        friend = new Gson().fromJson(user, Friend.class);
                        setPage(friend);
                    } catch (JSONException e) {

                    }
                }
            }
        });
    }

    private void setPage(Friend friend) {
        searchNc.setText(friend.petName);
        if (!TextUtils.isEmpty(friend.sex))
            if (TextUtils.equals(friend.sex, "1"))
                sex.setText("男");
            else
                sex.setText("女");

        else
            sex.setText("未填写");
        if (!TextUtils.isEmpty(friend.birthday))
            searchSr.setText(friend.birthday);
        else
            searchSr.setText("未填写");
        if (!TextUtils.isEmpty(friend.address))
            searchDq.setText(friend.address);
        else
            searchDq.setText("未填写");
        if (!TextUtils.isEmpty(friend.imageAddress) && !friend.imageAddress.startsWith("null"))
            Glide.with(this).load(friend.imageAddress)
                    .placeholder(R.drawable.myimg2).error(R.drawable.myimg2).
                    transform(new GlideCircleTransform(UIUtils.getContext()))
                    .into(searchImg);
    }


    /**
     * 添加好友
     * 请求地址 : app/user/getApplyState
     * 参数 :
     * id: 用户id   sign：签名 firendId :好友id
     * nonce：随机数  timestamp：时间戳
     * 签名字段 :
     * Id;firendId;nonce;timestamp外加key 秘钥
     */
    @OnClick(R.id.addFriends)
    public void onclick() {
        if (TextUtils.equals(userId, myID)) {
            ToastUtils.showToast("不能自己添加自己");
            return;
        }
        Map<String, Friend> contactList3 = DBManager.getInstance().getContactList3();
        Collection<Friend> values = contactList3.values();
        for (Friend friend : values) {
            if (TextUtils.equals(friend.id, this.friend.id)) {
                ToastUtils.showToast("该用户已经是您的好友了！");
                return;
            }
        }
        showDIalog();
        addContact();
    }

    //    添加联系人
    private void addContact() {
        String nonce = String.valueOf(new Random().nextInt());
        long l = System.currentTimeMillis();
        String signLogin = SignUtil.signLogin(name, pwd, SignUtil.getTimeStamp(l), nonce);
        OkHttpUtils.post()
                .url(SpKey.BASEURL + "/user/getApplyState")
                .addParams("id", myID)
                .addParams("sign", SignUtil.signForAddOthers(myID, userId, nonce, l, signLogin, loginId))
                .addParams("firendId", userId)
                .addParams("signLogin", signLogin)
                .addParams("loginId", loginId)
                .addParams("nonce", nonce)
                .addParams("timestamp", SignUtil.getTimeStamp(l))
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                progressDialog.dismiss();
                ToastUtils.showToast("网络异常，请稍后重试");
            }

            @Override
            public void onResponse(String response, int id) {
                PrintUtil.printRespones("添加联系人:",response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String state = jsonObject.optString("state");
                    if (TextUtils.equals(state, "1")) {
                        ToastUtils.showToast("添加请求已发送");
                    } else {
                        ToastUtils.showToast("添加请求已发送，请耐心等待");
                    }
                    progressDialog.dismiss();
//                    申请好友后，后台没有推送，无法知道申请信息，只能发送消息，手动刷新，后续再改
//                    sendBroadForUpdateContact();
                    finish();
                } catch (JSONException e) {

                }
            }
        });
    }

    /**
     * 发送广播更新好友列表
     */
    private void sendBroadForUpdateContact() {
        if (intent == null) {
            intent = new Intent();
            intent.setAction("updateFriendList");
        }
        sendBroadcast(intent);
    }

    private void showDIalog() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在添加..");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();
    }
}
